package cn.tonyandmoney.voicenotes

import android.Manifest
import android.os.Bundle
import android.os.Process
import android.view.Gravity
import cn.tonyandmoney.voicenotes.ui.MainActivity
import com.zlzsy.app.base.helper.PermissionHelper
import com.zlzsy.app.base.ui.BaseActivity
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.*
import java.util.concurrent.TimeUnit

/**
 * 启动页
 * 获取所需要的各项权限
 * 给用户一个等待的时间
 */
class SplashActivity : BaseActivity(), PermissionHelper.IPermissionView {


    private val mHelper: PermissionHelper by lazy { PermissionHelper(this, this) }

    override fun initView() {
        frameLayout {
            setBackgroundResource(R.color.grey)
            verticalLayout {
                padding = dip(20)
                progressBar {
                    title = "正在初始化..."
                }
                textView {
                    text = "正在初始化..."
                    textSize = 17f
                    setTextColor(resources.getColor(android.R.color.white))
                }
            }.lparams(wrapContent, wrapContent) {
                gravity = Gravity.CENTER
            }
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        val reqPermission = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.RECORD_AUDIO)

        val reqList = mHelper.check(reqPermission)
        if (reqList.isNotEmpty())
            mHelper.requestPermission(11, reqList.toTypedArray())
        else granted(11)
    }

    override fun granted(requestCode: Int) {
        startActivity<MainActivity>()
        finish()
    }

    override fun denied(requestCode: Int, permission: List<String>) {
        showLoadingDialog(R.string.can_not_require_permission)
        Observable.create<Int> { it.onNext(0);it.onComplete() }
                .delay(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .unsubscribeOn(Schedulers.newThread())
                .subscribe { Process.killProcess(Process.myPid()) }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        mHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

}